package org.spiderflow;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 测试阿里 ttl， 重复使用线程池线程，不会相互干扰
 *
 * @author kevin
 * @since 2022/7/17
 */
public class Test {
    /**
     * 初始化一个TransmittableThreadLocal，这个是继承了InheritableThreadLocal的
     */
    static TransmittableThreadLocal<String> local = new TransmittableThreadLocal<>();
    //static InheritableThreadLocal<String> local = new InheritableThreadLocal<>();
    //static ThreadLocal<String> local = new ThreadLocal<>();

    /**
     * 初始化一个长度为1的线程池，为了测试不同的线程任务运行后的相互影响
     */
    static ExecutorService poolExecutor = Executors.newFixedThreadPool(1);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Test test = new Test();
        test.test();
    }
    private void test() throws ExecutionException, InterruptedException {

        // 设置初始值
        local.set("天王老子");
        //！！！！ 注意：这个地方的Task是使用了TtlRunnable包装的
        Future future = poolExecutor.submit(TtlRunnable.get(new Task("任务1")));
        //Future future = poolExecutor.submit(new Task("任务1"));
        future.get();

        Future future2 = poolExecutor.submit(TtlRunnable.get(new Task("任务2")));
        //Future future2 = poolExecutor.submit(new Task("任务2"));
        future2.get();

        System.out.println("父线程的值："+local.get());
        poolExecutor.shutdown();
    }

    class Task implements Runnable{

        String str;
        Task(String str){
            this.str = str;
        }
        @Override
        public void run() {
            // 获取值
            System.out.println(Thread.currentThread().getName()+":"+local.get());
            // 重新设置一波
            local.set(str);
            System.out.println("设置后看看本身的值" + Thread.currentThread().getName()+ local.get());
        }
    }
}